package com.common.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * 图片保存到本地服务器工具类
 *
 * @author yanling
 * @date 2018/5/29
 */
public class ImageUtil {
    protected static final Log logger = LogFactory.getLog(ImageUtil.class);

    /**
     * 通过图片地址,将图片下载到本地服务器
     *
     * @param imageurl 图片原有地址
     * @param savepath 保存路径
     * @param name     图片名称
     * @return
     */
    public static void saveImageToDisk(String imageurl, String savepath, String name) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //构造URL
            URL url = new URL(imageurl);
            //获取连接
            URLConnection connection = url.openConnection();
            //设置请求超时为5s
            connection.setConnectTimeout(5 * 1000);
            //输入流
            inputStream = connection.getInputStream();
            //缓冲区
            byte[] bytes = new byte[1024];
            int length;
            File file = new File(savepath);
            if (!file.exists()) {
                file.mkdirs();
            }
            //输出流
            outputStream = new FileOutputStream(file.getPath() +File.separator + name);
            //读取图片
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            logger.info("================================ saveImageToDisk  SUCCESS !!!  +savePath:" + savepath);
        } catch (Exception e) {
            logger.info("================================ saveImageToDisk  FAIL !!! savepath:" + savepath + "erromsg" + e.getMessage());
        } finally {
            //关流
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
